package fdoj.eventInvitations.servlet;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import fdoj.eventInvitations.dao.PersonDao;
import fdoj.eventInvitations.dao.PersonDaoBean;
import fdoj.eventInvitations.entity.Person;

public class LoginController extends HttpServlet {
	@EJB
	private PersonDao personDao;

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			String email = request.getParameter("email");
			String password = request.getParameter("pass");
			if (email == null || password == null)
				throw new ServletException(
						"[LoginServlet] Illegal invocation: no email and/or password");

			Person person = personDao.login(email, password);
			if (person == null) {
				request.setAttribute("message", "wrongLogin");
				request.setAttribute("redirectURL", "");
				request.setAttribute("title", "redirection");
				request.getRequestDispatcher("/redirectPage.jsp").forward(request, response);
				return;
			}
			if (person.getRegToken().equals("true")) {
				HttpSession session = request.getSession(true);
				session.setAttribute("loggedUser", person);

				response.sendRedirect(response.encodeRedirectURL("./home"));
				return;
			}else{
				request.setAttribute("message", "notVerifiedEmail");
				request.setAttribute("redirectURL", "");
				request.setAttribute("title", "redirection");
				request.getRequestDispatcher("/redirectPage.jsp").forward(request, response);
				return;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		response.sendRedirect(response.encodeRedirectURL("./index"));
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}

}
